import type { TreeNode } from "@pkgs/interface";

/**
 * @func 根据树和节点获取父节点
 * @param list
 * @param id
 * @returns TreeNode[]
 */
export function getParentId(
  list: TreeNode[],
  id: number
): TreeNode[] | undefined {
  for (let item of list) {
    if (item.id === id) {
      return [item];
    }
    if (item.children) {
      let node = getParentId(item.children, id);
      if (node !== undefined) {
        return node.concat(item);
      }
    }
  }
}

/**
 * @func 根据树和节点获取树子节点
 * @param list
 * @param nodeId
 * @returns TreeNode[]
 */
export function getNodeTree(list: TreeNode[], nodeId: number) {
  let arr = [];
  for (let item of list) {
    if (item.id === nodeId) {
      arr.push(item);
      break;
    }
    if (item.children instanceof Array && item.children.length > 0) {
      const node: TreeNode[] = getNodeTree(item.children, nodeId);
      if (node.length > 0) {
        return node;
      }
    }
  }
  return arr;
}

/**
 * @func 根据节点ID获取节点路径
 * @param list 
 * @param nodeId 
 * @returns 
 */
export function findNodePathById(list: TreeNode[], nodeId: number): string {
  let path: string = ''
  for (let item of list) {
    if (item.id === nodeId) {
      path = item.path;
      break;
    }
    if (item.children instanceof Array && item.children.length > 0) {
      const node: string | undefined = findNodePathById(item.children, nodeId);
      if (node) {
        return node;
      }
    }
  }
  return path;
}
